﻿using System;
using System.Collections.Generic;
using System.Web;
using System.Drawing;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using log4net;

namespace SISCON.Util
{
    public class SaveUtil
    {
        public static string DEFAULT_SAVE_PATH = @"C:\inetpub\wwwroot\SISCON\uploads\";

        public static string SaveFile(byte[] fileBytes, string fileName, string saveToPath)
        {
            try
            {
                saveToPath = saveToPath == null ? DEFAULT_SAVE_PATH : saveToPath;

                if (fileBytes.LongLength > 0)
                {
                    CreateDirectory(saveToPath);
                    File.WriteAllBytes(EscapeFilePath(saveToPath + "/" + fileName), fileBytes);
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return saveToPath + @"\" + fileName;
        }

        public static void MoveFile(string fileName, string currentPath, string moveToPath)
        {
            CreateDirectory(moveToPath);
            if (File.Exists(moveToPath + "/" + fileName))
            {
                File.Delete(moveToPath + "/" + fileName);
            }
            File.Move(currentPath + "/" + fileName, moveToPath + "/" + fileName);
        }

        private static void DeleteFile(string filePath, string fileName)
        {
            if (filePath != null && fileName != null)
            {
                if (File.Exists(filePath + "/" + fileName))
                {
                    File.Delete(filePath + "/" + fileName);
                }
            }
        }

        private static string FileNameWithoutExtension(string fileName)
        {
            return fileName.Substring(0, fileName.LastIndexOf("."));
        }

        private static void CreateDirectory(String path)
        {
            path = EscapeFilePath(path);
            //Create the directory
            if (!System.IO.Directory.Exists(path))
            {
                DirectoryInfo dir = System.IO.Directory.CreateDirectory(path);
            }
        }

        private static string EscapeFilePath(string filePath)
        {
            string escapedFilePath = "";

            escapedFilePath = filePath.Replace(@"\", "/");

            return escapedFilePath;
        }
    }
}